<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <%@ include file="/common/common-css.v2.jsp" %>
    <style>
        button {
            display: inline-block;
            box-sizing: border-box;
            height: 30px;
            min-width: 100px;
            outline: none;
            border: 0;
            background-color: #438EB9;
            color: #FFF;
            text-align: center;
            box-shadow: 0 0 3px rgba(0, 0, 0, .2);
            transition: background-color .2s;
        }

        button:hover {
            background-color: #62A8D1;
        }

        button:active {
            background-color: #206892;
        }

        button.warn {
            background-color: rgb(255, 66, 83)
        }

        button.warn:hover {
            background-color: #FF8484;
        }

        button.warn:active {
            background-color: #CE5A5A;
        }

        button.forbidden {
            background-color: #B7B7B7;
            cursor: not-allowed !important;
        }

        .menu-mask {
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            background-color: rgba(225, 225, 225, .7);
            display: none;
            text-align: center;
        }

        .menu-mask .info {
            margin-top: 200px;
        }

        .menu-sub {
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, .7);
            display: none;
        }

        .menu-container-sub {
            position: absolute;
            left: 100px;
            right: 100px;
            top: 100px;
            bottom: 100px;
            background: #fff
        }

        .menu-title {
            width: 100%;
            height: 35px;
            text-align: center;
            line-height: 35px;
            background-color: #79c5f1;
            font-weight: bold;
            color: white;
            text-shadow: 1px 1px 1px rgba(0, 0, 0, .2);
        }

        .close-sub {
            width: 100px;
            height: 100%;
            float: right;
            background-color: rgb(255, 66, 83);
            font-size: 20px;
            line-height: inherit;
            transition: background-color .2s;
        }

        .close-sub:hover {
            background-color: #FF8484;
        }

        .menu-container-main {
            padding: 10px;
        }

        .btn-container {
            margin-bottom: 15px;
        }

        .btn-container * {
            margin-right: 20px;
        }

        .menu-table {
            width: 100%;
            border-top: 1px solid #ddd;
            border-collapse: collapse;
            margin-bottom: 15px;
        }

        .menu-table input[type="text"], #menu-table select {
            width: 100%;
        }

        .menu-table tr {
            border-left: 1px solid #ddd;
            border-bottom: 1px solid #ddd;
        }

        .menu-table th {
            padding: 15px 15px;
            border-right: 1px solid #ddd;
            text-align: center;
        }

        .menu-table td {
            padding: 15px 15px;
            border-right: 1px solid #ddd;
            background: #fff;
            text-align: center;
        }

        .menu-table thead {
            color: #547ea8;
            font-weight: bold;
            font-size: 13px;
        }

        .menu-table thead tr {
            background-image: linear-gradient(to bottom, #f8f8f8 0, #ececec 100%);
        }
    </style>
    <script src="${ctx}/ace/js/jquery.min.js"></script>
</head>
<body>
<div class="menu-mask">
    <div class="info">加载中...</div>
</div>
<div class="menu-sub">
    <div class="menu-container-sub">
        <div class="menu-title">编辑子菜单
            <div class="close-sub" onclick="closeWindow()">X</div>
        </div>
        <div class="menu-container-main">
            <div class="btn-container">
                <button onclick="addSubMenu()">添加菜单</button>
                <button class="warn" onclick="deleteSubMenu()">删除菜单</button>
                <%--<button onclick="displaySubMenu()">显示数据</button>--%>
            </div>
            <table id="menu-table-sub" class="menu-table">
                <thead>
                <tr>
                    <th style="width: 100px">菜单顺序</th>
                    <th style="width: 200px">菜单名称</th>
                    <th style="width: 150px;">菜单类型</th>
                    <th>菜单参数</th>
                </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>
</div>
<div class="menu-main">
    <div class="menu-container-main">
        <div class="btn-container">
            <button onclick="addMenu()">添加菜单</button>
            <button class="warn" onclick="deleteMenu()">删除菜单</button>
            <%--<button onclick="displayMenu()">显示数据</button>--%>
            <label for="weixin-account">配置微信号:</label>
            <select id="weixin-account">
                <option value="4">测试公众号</option>
                <option value="8105">菠萝优选</option>
                <option value="8103">有点零花</option>
                <option value="8119">菠萝钱柜</option>
                <option value="8120">西瓜钱柜</option>
                <option value="8121">熊花花</option>
                <option value="8118">布拿拿管卡花</option>
                <option value="8109">宝贝零花</option>
                <option value="8110">小熊零花</option>
                <option value="8111">钱哆哆</option>
                <option value="8112">任我财</option>
                <option value="8113">吾小钱</option>
                <option value="8114">喜乐花</option>
                <option value="8115">菠萝米花</option>
                <option value="8116">每日花</option>
                <option value="8117">菠萝花</option>
                <option value="8122">欢乐零花</option>
                <option value="8123">欢乐钱柜</option>
                <option value="8126">菠萝零花</option>
                <option value="8130">欢乐有钱</option>
                <option value="8131">优选锦鲤</option>
            </select>
            <label for="menu-remark">配置备注:</label>
            <input type="text" id="menu-remark" placeholder="配置备注(选填)">
        </div>
        <table id="menu-table-main" class="menu-table">
            <thead>
            <tr>
                <th style="width: 100px">菜单顺序</th>
                <th style="width: 200px">菜单名称</th>
                <th style="width: 150px;">菜单类型</th>
                <th>菜单参数</th>
                <th>菜单功能</th>
            </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
        <div class="btn-container">
            <button id="save-btn" onclick="save()">保存配置</button>
            <button id="get-config" onclick="getConfig()">获取最新配置</button>
            <button id="apply-config" onclick="applyConfig()">应用最新配置</button>
        </div>
    </div>
</div>
</body>
<script type="text/javascript">
    // DOM
    var mask = $('.menu-mask');

    var tableMain = $('#menu-table-main');
    var tbodyMain = tableMain.find('tbody');

    var tableSub = $('#menu-table-sub');
    var tbodySub = tableSub.find('tbody');

    var subWindow = $('.menu-sub');
    var subWindowContext = [];

    var account = $('#weixin-account');
    var saveBtn = $('#save-btn');
    var getBtn = $('#get-config');
    var applyBtn = $('#apply-config');
    var remark = $('#menu-remark');

    // Model
    var models = [];
    {
        function getVM(isSub, index, name, type, param) {
            var dom;
            if (isSub) {
                dom = $('<tr><td class="index"></td><td><input type="text" class="name"/></td><td><select class="type"><option value="view" selected>跳转页面</option><option value="click">点击事件</option></select></td><td><input type="text" class="param"/></td></tr>');
            }
            else {
                dom = $('<tr><td class="index"></td><td><input type="text" class="name"/></td><td><select class="type"><option value="view" selected>跳转页面</option><option value="click">点击事件</option></select></td><td><input type="text" class="param"/></td><td><button class="edit-sub">编辑子菜单</button></td></tr>');
            }

            var model = {
                dom: dom,
                index: -1,
                name: '',
                type: '',
                param: '',
                list: []
            };

            var out = {
                // getter
                getDom: function () {
                    return model.dom;
                },
                getIndex: function () {
                    return model.index;
                },
                getName: function () {
                    return model.name;
                },
                getType: function () {
                    return model.type;
                },
                getParam: function () {
                    return model.param;
                },
                getList: function () {
                    return model.list;
                },
                // setter
                setIndex: function (index) {
                    model.index = index;
                    dom.find('.index').html(index + 1);
                },
                setName: function (name) {
                    model.name = name;
                    dom.find('.name').val(name);
                },
                setType: function (type) {
                    model.type = type;

                    switch (type) {
                        case 'view':
                        {
                            dom.find('select.type option[value="view"]').prop('selected', true);
                            if (this.getParam().indexOf('http://') !== 0) {
                                this.setParam('http://' + this.getParam());
                            }
                            break;
                        }

                        case 'click':
                        {
                            dom.find('select.type option[value="click"]').prop('selected', true);
                            break;
                        }

                        default:
                        {
                            throw 'unsupported type';
                        }
                    }
                },
                setParam: function (param) {
                    if (this.getType() === 'view' && param.indexOf('http://') !== 0) {
                        model.param = 'http://' + param;
                        dom.find('.param').val(model.param);
                    }
                    else {
                        model.param = param;
                        dom.find('.param').val(model.param);
                    }

                }
            };

            // 绑定事件
            dom.on('change', '.name', function () {
                var newVal = $(this).val();
                newVal = newVal.replace(/\s/g, '');
                if (!newVal) {
                    alert('菜单名称不能为空');
                    var oldVal = out.getName();
                    out.setName(oldVal);
                }
                else {
                    out.setName(newVal);
                }
            });

            dom.on('change', '.type', function () {
                var newVal = $(this).val();
                out.setType(newVal);
            });

            dom.on('change', '.param', function () {
                var newVal = $(this).val();
                var oldVal;
                newVal = newVal.replace(/\s/g, '');
                if (!newVal) {
                    alert('参数不能为空');
                    oldVal = out.getParam();
                    out.setParam(oldVal);
                }
                else if (out.getType() === 'view' && newVal.indexOf('http://') !== 0) {
                    alert('跳转参数必须以"http://"开始');
                    oldVal = out.getParam();
                    out.setParam(oldVal);
                }
                else {
                    out.setParam(newVal);
                }
            });

            if (!isSub) {
                dom.on('click', '.edit-sub', function () {
                    openWindow(out.getList());
                });
            }

            // 初始化
            out.setIndex(index);
            out.setName(name);
            out.setType(type);
            out.setParam(param);
            return out;
        }
    }

    function addMenu() {
        var index = models.length;
        if (index == 3) {
            alert('最多只能添加3个一级菜单');
            return;
        }
        var name = '菜单' + (index + 1);
        var vm = getVM(false, index, name, 'view', 'http://');

        models.push(vm);
        tbodyMain.append(vm.getDom())
    }

    function addSubMenu() {
        var index = subWindowContext.length;
        if (index == 5) {
            alert('最多只能添加5个而二级菜单');
            return;
        }
        var name = '子菜单' + (index + 1);
        var vm = getVM(true, index, name, 'view', 'http://');

        subWindowContext.push(vm);
        tbodySub.append(vm.getDom())
    }

    function deleteMenu() {
        if (models.length != 0) {
            var vm = models.pop();
            vm.getDom().remove();
        }
    }

    function deleteSubMenu() {
        if (subWindowContext.length != 0) {
            var vm = subWindowContext.pop();
            vm.getDom().remove();
        }
    }

    function displayModel(out) {
        var obj = {};
        obj.index = out.getIndex();
        obj.name = out.getName();
        obj.type = out.getType();
        obj.param = out.getParam();
        console.log(JSON.stringify(obj));
    }

    function displayMenu() {
        console.clear();
        for (var i = 0; i < models.length; ++i) {
            var out = models[i];
            displayModel(out);
            var list = out.getList();
            if (list.length != 0) {
                console.log('==========sub menu of "' + out.getName() + ' START"==========');
                for (var j = 0; j < list.length; ++j) {
                    displayModel(list[j]);
                }
                console.log('==========sub menu of "' + out.getName() + ' END"==========');
            }
        }
    }

    function displaySubMenu() {
        console.clear();
        for (var i = 0; i < subWindowContext.length; ++i) {
            var out = subWindowContext[i];
            displayModel(out);
        }
    }

    function openWindow(list) {
        subWindowContext = list;
        for (var i = 0; i < subWindowContext.length; ++i) {
            tbodySub.append(subWindowContext[i].getDom());
        }
        subWindow.fadeIn();
    }

    function closeWindow() {
        subWindow.fadeOut(function () {
            tbodySub.find('tr').detach();
        });
    }

    function convertModel2Obj(out) {
        var obj = {
            name: out.getName()
        };

        var list = out.getList();
        if (list && list.length !== 0) {
            obj.sub_button = [];
            for (var i = 0; i < list.length; ++i) {
                var tmp = list[i];
                obj.sub_button.push(convertModel2Obj(tmp));
            }
        }
        else {
            obj.type = out.getType();
            switch (obj.type) {
                case 'view':
                {
                    obj.url = out.getParam();
                    break;
                }
                case 'click':
                {
                    obj.key = out.getParam();
                    break;
                }

                default:
                {
                    throw 'unsupported type';
                }
            }
        }

        return obj;
    }

    function exportCurrentConfig() {
        var obj = {};
        obj.button = [];
        for (var i = 0; i < models.length; ++i) {
            obj.button.push(convertModel2Obj(models[i]))
        }
        return obj;
    }

    function initModel(config, index, isSub) {
        var name;
        var vm;

        if (config.sub_button && config.sub_button.length !== 0) {
            name = config.name;
            vm = getVM(false, index, name, 'view', 'http://');

            var list = config.sub_button;
            for (var i = 0; i < list.length; ++i) {
                var tmp = list[i];
                var tmpVm = initModel(tmp, i, true);
                vm.getList().push(tmpVm);
            }
        }
        else {
            name = config.name;
            var type = config.type;
            var param;
            switch (type) {
                case 'view':
                {
                    param = config.url;
                    break;
                }
                case 'click':
                {
                    param = config.key;
                    break;
                }
                default:
                {
                    throw 'unsupported type';
                }
            }

            vm = getVM(isSub, index, name, type, param);
        }

        return vm;
    }

    function fillDate(data, rmk) {
        models = [];
        subWindowContext = [];

        tbodyMain.find('tr').remove();
        tbodySub.find('tr').remove();

        if (rmk) {
            remark.val(rmk);
        }

        var list = data.button;
        for (var i = 0; i < list.length; ++i) {
            var vm = initModel(list[i], i, false);
            models.push(vm);
            tbodyMain.append(vm.getDom())
        }
    }

    function save() {
        if (models.length === 0) {
            alert('不能保存空的菜单配置');
            return;
        }

        var data = {};
        data.config = exportCurrentConfig();
        data.account = window.parseInt(account.val());
        data.remark = remark.val();

        var url = '${ctx}' + '/weixin/weixin_menu_submit.action';
        $.ajax({
            url: url,
            contentType: 'application/json',
            type: 'POST',
            cache: false,
            beforeSend: function () {
                mask.fadeIn();
            },
            complete: function () {
                mask.fadeOut();
            },
            data: JSON.stringify(data),
            dataType: 'json',
            error: function () {
                alert('网络错误, 请稍后重试');
            },
            success: function (d) {
                if (!d) {
                    alert('服务器错误, 无返回数据');
                    return;
                }

                if (d.status != null && d.msg != null) {
                    if (d.status === 0) {
                        alert('保存成功');
                    }
                    else {
                        alert('保存失败, 错误码: ' + d.status + ', 错误信息: ' + d.msg);
                    }
                }
                else {
                    alert('服务器错误, 返回数据无法解析, 返回数据见日志');
                    console.log(d.toString());
                }
            }
        });
    }

    function getConfig() {
        var weixinAccount = account.val();
		console.log(weixinAccount);
        var url = '${ctx}' + '/weixin/weixin_menu_last.action';
        $.ajax({
            url: url,
            type: 'POST',
            cache: false,
            beforeSend: function () {
                mask.fadeIn();
            },
            complete: function () {
                mask.fadeOut();
            },
            data: {account: weixinAccount},
            dataType: 'json',
            error: function () {
                alert('网络错误, 请稍后重试');
            },
            success: function (d) {
            	console.log(d);
                if (!d) {
                    alert('服务器错误, 无返回数据');
                    return;
                }

                if (d.status != null && d.msg != null) {
                    if (d.status === 0) {
                        var raw = d.data;
                        var rmk = d.remark;
                        console.log("raw: " + raw);
                        console.log("rmk: " + rmk);
                        console.log();
                        if (raw) {
                            raw = raw.replace(/\\/g, '');
                            raw = eval('(' + raw + ')');
                            fillDate(raw, rmk);
                        }
                    }
                    else {
                        alert('获取失败, 错误码: ' + d.status + ', 错误信息: ' + d.msg);
                    }
                }
                else {
                    alert('服务器错误, 返回数据无法解析, 返回数据见日志');
                    console.log(d.toString());
                }
            }
        });
    }

    function applyConfig() {
        var weixinType = account.val();

        var url = '${ctx}' + '/weixin/weixin_menu_apply.action';
        $.ajax({
            url: url,
            type: 'POST',
            cache: false,
            beforeSend: function () {
                mask.fadeIn();
            },
            complete: function () {
                mask.fadeOut();
            },
            data: {weixinType: weixinType},
            dataType: 'json',
            error: function () {
                alert('网络错误, 请稍后重试');
            },
            success: function (d) {
                if (!d) {
                    alert('服务器错误, 无返回数据');
                    return;
                }

                if (d.status != null && d.msg != null) {
                    var weixinData = {};
                    if (d.weixinRsp) {
                        var rsp = d.weixinRsp.replace(/\\/g, '');
                        weixinData = eval('(' + rsp + ')');
                        console.log('微信响应: ' + JSON.stringify(weixinData));
                    }

                    if (d.status === 0) {
                        if (weixinData.errcode === 0 && weixinData.errmsg === 'ok') {
                            alert('应用菜单配置成功');
                        }
                        else {
                            alert('应用菜单配置失败, 微信返回信息: ' + JSON.stringify(weixinData));
                        }
                    }
                    else {
                        alert('应用失败, 状态码: ' + d.status + ', 状态信息: ' + d.msg);
                    }

                }
                else {
                    alert('服务器错误, 返回数据无法解析, 返回数据见日志');
                    console.log(d.toString());
                }
            }
        });
    }

    window.onload = function () {
        getConfig();
    }
</script>
</html>